#include <Arduino.h>
#include <Preferences.h>
#include "../TdrLiquidSensorGlobal.hpp"
#include "Identity.hpp"
/*
Define the following paras to overwrite
  ANSWER_WHO
  VERSION
*/

#define NAME_SPACE "PROJ_ID"

#define VAR_ENTRY_WHICH "WHICH"
String which;
String who;
String version;
void loadWhich();
void saveWhich();

Preferences preferencesIdentity;

void Identity::init(const char* whoIn, const char* versionIn) {
	if (!preferencesIdentity.begin(NAME_SPACE, true))
	{
		preferencesIdentity.end();
	}

	loadWhich();
	who = whoIn;
	version = versionIn;

	preferencesIdentity.end();
}

#define StartWith(a,b) strncmp(a, b, strlen(b)) == 0

uint64_t chipid = 0;
bool Identity::parseCmd(const char* cmd) {
	if (StartWith(cmd, "who") || StartWith(cmd, "WHO")) {
		return printWho();
	}
	else if (StartWith(cmd, "which") || StartWith(cmd, "WHICH")) {
		return printWhich();
	}
	else if (StartWith(cmd, "set which")) {
		cmd += sizeof("set which");
		which = cmd;
		int idx = which.length() - 1;
		while (idx > 0) {
			if (which[idx] == '\n' || which[idx] == '\r') {
				which[idx] = '\0';
				idx--;
			}
			else {
				break;
			}
		}
#define META_REPORT_SET_WHICH "New ID %s\r\n"
		sprintf(Global::outputbuf, META_REPORT_SET_WHICH,
			which.c_str());
		saveWhich();
		return true;
	}
	else if (StartWith(cmd, "version") || StartWith(cmd, "VERSION")) {
		sprintf(Global::outputbuf, "%s\r\n", version.c_str());
		return true;
	}
	return false;
}

bool Identity::printWho() {
#define META_REPORT_UUID_FORMAT 	"%s\r\nUUID:{%016llx}\r\n"    
	if (chipid == 0) {
		chipid = ESP.getEfuseMac();
	}
	sprintf(Global::outputbuf, META_REPORT_UUID_FORMAT,
		who.c_str(),
		chipid);
	Serial.print(Global::outputbuf);
	return true;
}

bool Identity::printWhich() {
#define META_REPORT_WHICH "%s\r\n"
	sprintf(Global::outputbuf, META_REPORT_WHICH,
		which.c_str());
	Serial.print(Global::outputbuf);
	return true;
}

void loadWhich() {
	which = preferencesIdentity.getString(VAR_ENTRY_WHICH);
}

void saveWhich() {
	if (!preferencesIdentity.begin(NAME_SPACE, false))
	{
		preferencesIdentity.end();
	}

	preferencesIdentity.putString(VAR_ENTRY_WHICH, which);

	preferencesIdentity.end();
}